angular.module('UCX.Cmis')
.directive('cloudReadingShare',(CmisService, localStorageService, ModelService,$window,$timeout, $uibModal, Utils, $translate, $q, ApiService)->

  scope:{
    file:'=',
    currentScope:'='
  }

  #  http://codepen.io/prophet_w/pen/GWjejg
  restrict:'C'
#  replace:true
  template:'
      <!-- Trigger the modal with a button -->
      <span ng-click="openShareModal(file)">

      </span>
      <!-- Modal -->
  '
  link:(scope, element, attr)->

    if !window.CloudReading
      window.CloudReading={}
    window.CloudReading.Utils =Utils
    window.CloudReading.translate =$translate
    lang = Utils.getLanguage()
    $translate.use lang
    scope.openModal = (file)->
      modalInstance = $uibModal.open({
        ariaLabelledBy: 'modal-title'
        ariaDescribedBy: 'modal-body'
        templateUrl: 'template-path/new-share.html',
        controller: 'ModalInstanceCtrl',
        controllerAs: '$ctrl',
#        windowClass:'cloud-reading-shared-modal'
        windowTopClass:'cloud-reading-shared-modal'
        backdropClass:'cloud-reading-shared-modal-backdrop'
        backdrop:'static'
        openedClass:'cloud-reading-shared-modal-open'
        resolve: {
          file: ()->
            file
        },
        backdrop: 'static'
      })

    $('body .mailTo').on('click',()->
      Utils.sendGaEvent('Share setting','Social share','sendEmail')
    )



    scope.getObjectInfoById=(documentId,successfulCallback)->
      console.log("documentId: " + documentId)
      documentId = documentId.split(",")[0] # because cmis does not keep all doc versions.
      console.log("documentId: " + documentId)
      console.log(CmisService)
      console.log(CmisService.session)
      console.log(CmisService.session.defaultRepository)
      if CmisService.session && CmisService.session.defaultRepository
        CmisService.session.getObject(documentId,'latest',{
          includeACL: true
          includeAllowableActions:true
        }).ok (data)->
          successfulCallback && successfulCallback(data)
        .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
          console.log(error)
      else
        CmisService.session.loadRepositories().ok (res)->
          console.log 'repositroy'
          console.log res
          CmisService.session.defaultRepository = res['fxcld']
          localStorageService.set "rootFolderUrl" , res['fxcld']['rootFolderUrl']
          CmisService.session.getObject(documentId,'latest',{
            includeACL: true
            includeAllowableActions:true
          }).ok (data)->
            successfulCallback && successfulCallback(data)
          .notOk (error)->
            if Utils.handleCmis401Error(error)
              return
            console.log(error)
        .notOk((error)->
          if Utils.handleCmis401Error(error)
            return
          console.log(error)
        )
    scope.handleShareFromPhantom = ()->
      if !(WebPDF.ViewerInstance && WebPDF.ViewerInstance.getCMISObjectId && window.PhantomOnline && window.PhantomOnline.uploadToCMIS)
        console.log(WebPDF.ViewerInstance)
        console.log(WebPDF.ViewerInstance.getCMISObjectId)
        console.log window.PhantomOnline
        console.log window.PhantomOnline.uploadToCMIS
        return false

      # cmis file get cmisId
      documentId = WebPDF.ViewerInstance.getCMISObjectId()
#      if !documentId
#        if location.href.indexOf('object_id')>-1
#          url = location.href.split('?')[1]
#          urlObject = Utils.urlParaToObj(url)
#          console.log(urlObject)
#          documentId = urlObject['object_id']
#        else
#          documentId=''
      # local file has saved right now and has a cmisId from temp @var
      if !documentId
        if window.PhantomOnline
          localFileUuid = window.PhantomOnline.getUUID()
          if(window.PhantomOnline.uuidMapCmisId && window.PhantomOnline.uuidMapCmisId[localFileUuid])
            documentId = window.PhantomOnline.uuidMapCmisId[localFileUuid]
          else
            documentId=''
        else
          documentId=''

      uploadToCmis = (fileUrl,successfulCallback)->
        window.PhantomOnline.uploadToCMIS(fileUrl,(data)->
          successfulCallback && successfulCallback(data);
          console.log('======== succ data =========')
          console.log(data)
          if data.code == 0
            Utils.warning(data.message)
          if !data.succinctProperties
            data.succinctProperties = data.properties
          data.acl.aces =Utils.formatAcl(data.acl)
          if !data.allowableActions
            data.allowableActions = data.allowable_actions
          file = ModelService.createDocument(data)
          console.log('====share DocModified====');
          currentEmail = Utils.getCookie('currentEmail');
          if file.createdBy.id == currentEmail
            scope.openModal(file)
          else
            Utils.warning($translate.instant('only_owner_can_set_permission'))
        )
      # cmis file then get info
      if documentId
        Utils.connectCmis()
        if WebPDF.ViewerInstance.isDocModified()
          #save share file
          if !WebPDF.Engine.isJR
            console.log('====getDocumentUrl====')
            WebPDF.ViewerInstance.getDocumentUrl((fileUrl)->
              # 调用 webpdf 提供接口显示 uploading
              WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
              uploadToCmis(fileUrl,(data)->
                # 如果上传成功，调用webpdf方法，讲 modify flag 重置为 false
                WebPDF.ViewerInstance.setModifyState(false)
                WebPDF.closeWaiting();
              )
            ,
              ()->
                Utils.warning('Get Document Url Failed')
            )
          else
            console.log('====getDocumentBuffer====')
            WebPDF.ViewerInstance.getDocumentBuffer((fileArrayBuffer)->
              WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
              uploadToCmis(fileArrayBuffer,(data)->
                # 如果上传成功，调用webpdf方法，讲 modify flag 重置为 false
                WebPDF.ViewerInstance.setModifyState(false)
                WebPDF.closeWaiting();
              )
            ,
              ()->
                Utils.warning('Get Document Buffer Failed')
            )
        else
          scope.getObjectInfoById(documentId,(data)->
            file = ModelService.createDocument(data)
            currentEmail = Utils.getCookie('currentEmail');
            console.log('====share NOT DocModified====');
            console.log(documentId);
            console.log(data);
            console.log(file);
            console.log(currentEmail);
            if file.createdBy.id == currentEmail
              scope.openModal(file)
            else
              Utils.warning($translate.instant('only_owner_can_set_permission'))
          )
      else
        # not cmis file then upload
#        uploadToCmis = (fileUrl)->
#          window.PhantomOnline.uploadToCMIS(fileUrl,(data)->
#            console.log('======== succ data =========')
#            console.log(data)
#            if data.code == 0
#              Utils.warning(data.message)
#            if !data.succinctProperties
#              data.succinctProperties = data.properties
#            data.acl.aces =Utils.formatAcl(data.acl)
#            if !data.allowableActions
#              data.allowableActions = data.allowable_actions
#            file = ModelService.createDocument(data)
#            scope.openModal(file)
#          )
        Utils.connectCmis()
        if !WebPDF.Engine.isJR
          console.log('====getDocumentUrl====')
          WebPDF.ViewerInstance.getDocumentUrl((fileUrl)->
            WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
            uploadToCmis(fileUrl,(data)->
              WebPDF.ViewerInstance.setModifyState(false)
              WebPDF.closeWaiting();
            )
          ,
            ()->
              Utils.warning('Get Document Url Failed')
          )
        else
          console.log('====getDocumentBuffer====')
          WebPDF.ViewerInstance.getDocumentBuffer((fileArrayBuffer)->
            WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
            uploadToCmis(fileArrayBuffer,(data)->
              WebPDF.ViewerInstance.setModifyState(false)
              WebPDF.closeWaiting();
            )
          ,
            ()->
              Utils.warning('Get Document Buffer Failed')
          )

    scope.openShareModal = (file)->

      #  preview page
      if window.PhantomOnline
        if(!localStorage.getItem('userInfo'))
          # phantom 未登录
          if window.PhantomOnline && window.PhantomOnline.showSignInModal
            window.PhantomOnline.showSignInModal(()->
              scope.handleShareFromPhantom()
            )
            return true
        else
          # phantom 登录用户
          console.log('============>')
          console.log('============>')
          scope.handleShareFromPhantom()
          console.log window.location.href
      else if window.FX
        # 插件
        Utils.connectCmis()
        if window.localStorage
          fileInfo = JSON.parse(localStorage.getItem('share_plugin_cmis_file'))
          cmisFileObj = ModelService.createDocument(fileInfo)
          scope.openModal cmisFileObj
        else
          fileId = Utils.getCookie('share_plugin_cmis_file_id')
          scope.getObjectInfoById(fileId,(data)->
            file = ModelService.createDocument(data)
            scope.openModal(file)
          )
      else
        #  not preview page
        #  every time the latest acl
        Utils.showLoading()
        parentFolder=file.getParent()
        if parentFolder.isCDRMFolder() && !file.cDocId
          cmisId=file.id
          if decodeURIComponent(file.id).indexOf(',')>-1
            cmisId=file.id
          else
            cmisId=file.id+','+file.versionLabel
          $q.all([ApiService.getCDocInfoByCmisId(cmisId),file.getAces(null,null,true)]).then((arr)->
            console.log(arr)
            cDrmInfo=arr[0]
            if cDrmInfo && cDrmInfo.ret==0
              file.cDocId=cDrmInfo.data.cDocID
            $timeout(()->
              Utils.closeLoading()
            ,300)
            scope.openModal(file)
          )
        else
          file.getAces(()->
            $timeout(()->
              Utils.closeLoading()
            ,300)

            scope.openModal(file)
          ,(err)->
            $timeout(()->
              Utils.closeLoading()
            ,300)
            console.log(err)
          ,true)


      #  modal style is here http://codepen.io/prophet_w/pen/KWqKgj?editors=1100
#      CmisService.getAces(file.id,(data)->
#
#      )

#    scope.$watch(()->
#      attr.id
#    ,()->
#      init()
#    )
)
.controller('ModalInstanceCtrl',($scope,file,$uibModalInstance,$timeout,$compile,$sce,Utils, $window, $uibPosition,CmisService, localStorageService, ApiService, ModelService, $translate, $q)->
  $scope.file=file
#  sourceFolder=file.getParent()
#  $scope.isCpdfDoc=if sourceFolder.isCDRMFolder() then true else false
  $scope.isCpdfDoc=decodeURIComponent(@path).indexOf(decodeURIComponent(CmisService.path+'/ConnectedPDF/cDRM'))>-1
  $scope.changed = false
  $scope.showSendEmail = true
  $scope.requesting=false
  $scope.showLoading=()->
    $scope.requesting=true

  $scope.hideLoading=()->
    $scope.requesting=false
  adjustModalHeight = ()->
    $('.cloud-reading-shared-modal .modal-dialog').height('auto')
    if($('body').height()<$('.cloud-reading-shared-modal .modal-dialog').height())
      $('.cloud-reading-shared-modal .modal-dialog').height($('body').height())
      $('.cloud-reading-shared-modal .modal-dialog').css({'overflow-y':'auto'})
    else
      $('.cloud-reading-shared-modal .modal-dialog').height('auto')
      $('.cloud-reading-shared-modal .modal-dialog').css({'overflow-y':'hidden'})
  window.onresize = ()->
    adjustModalHeight()
  $uibModalInstance.opened.then(()->
    setTimeout(()->
      adjustModalHeight()
    ,300)
  )
  $scope.placeholder='enter_email_address'
  $scope.isMobile=false
  getMobileOperatingSystem=()->
    userAgent = navigator.userAgent || navigator.vendor || window.opera;
    if (/windows phone/i.test(userAgent))
      return "Windows Phone"
    if (/android/i.test(userAgent))
      return "Android"
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream)
      return "iOS"
    return false
  if(getMobileOperatingSystem())
    $scope.isMobile=true

  if window.FX && window.FX.app && window.FX.app.getInfo
    if window.localStorage
      fxAppVersion = localStorage.getItem('share_plugin_app_version') || 10
    else
      fxAppVersion = window.sharePlugin.localStorage.getItem('share_plugin_app_version') || 10
    if(parseFloat(fxAppVersion) >= 1.1)
      $scope.showSendEmail = true
    else
      $scope.showSendEmail = false
  lang = Utils.getLanguage()
  if window.FX && window.FX.app && window.FX.app.getInfo
    if window.localStorage
      lang = localStorage.getItem('share_plugin_lang').split('-')[1]
    else
      lang = window.sharePlugin.localStorage.getItem('share_plugin_lang').split('-')[1]
  $translate.use lang
  if(window.PhantomOnline && !currentUserId)
    currentUserId = localStorage.getItem('currentEmail')
  $scope.getSharedInfo = ()->
    ApiService.getSharedInfo(file,null,(data)->
      Utils.sendGaEvent('Document','Share file','getSharedInfo')
      $scope.loading=false
      $scope.waitingForLink = false
      # can_download status
      if data && data.share && data.share.can_download==1
        file.disableDownload = false
      else
        file.disableDownload = true
      # share link
      if data && data.share && data.share.short_url
#        if (window.cReaderEnable=='1'||window.cReaderEnable==true||window.cReaderEnable==1) && window.cReaderUrl
#          shareCode=data.share.short_code
#          file.sharedLink = window.cReaderUrl+'/share/'+shareCode
#        else
        file.sharedLink = data.share.short_url
        $scope.fileLink = file.sharedLink
      $scope.disableDownload = file.disableDownload
      if data && data.cmis_document && !data.cmis_document.succinctProperties
        data.cmis_document.succinctProperties = data.cmis_document.properties
      data.cmis_document.acl.aces = Utils.formatAcl(data.cmis_document.acl)
      if data && data.cmis_document && !data.cmis_document.allowableActions
        data.cmis_document.allowableActions = data.cmis_document.allowable_actions
      newFile = ModelService.createDocument(data.cmis_document)
#      console.log('====newFile')
#      console.log(newFile)
      file.description=newFile.description
      file.aces=newFile.aces
      $scope.everyonePermission = $scope.getEveryonePermission(file)[1] || 'smx:none'
#      file.sharedLink = sharedLink.phantom_online_url
#      https://jira.foxitsoftware.cn/browse/WEBPDF-5599
#      file.sharedLink =newFile.sharedLink
#      $scope.fileLink = file.sharedLink


      $scope.hasSharedLink = true
      $scope.generateBigQrcode()
      $timeout(()->
        $scope.$apply()
      )
    ,
      (err)->
        $scope.loading=false
        Utils.warning(err)
        console.log err
        $timeout(()->
          $scope.$apply()
        )
    )

  if file.sharedLink
    $scope.hasSharedLink = true
    $scope.sharedLink = file.sharedLink
  else
    $scope.hasSharedLink = false
  $scope.disableDownload = file.disableDownload
  if !file.sharedLink
    $scope.waitingForLink = true
    $scope.getSharedInfo()




  currentUserEmail = localStorageService.get('userEmail')

  $scope.everyonePermissionToActionMap={
    'cmis:read':$translate.instant('anyone_has_link_can_view')
    'smx:none':$translate.instant('special_people_can_view')
    'cmis:write':$translate.instant('anyone_has_link_can_comment')
  }
  $scope.permissionToActionMap={
    'cmis:read':$translate.instant('can_view')
#    'cmis:write':$translate.instant('can_comment')
  }

  ###
  #  user list begin
  ###
  $scope.generateUserList = ()->
    fileOwner={
      userAvatar : file.createdBy.getAvatar()
      userName : file.createdBy.getName()
      userId : file.createdBy.id
      action : $translate.instant('is_owner')
      isOwner:true
    }
    $scope.userList=[]
    $scope.userList.push(fileOwner)
    getActionByPermission = (permission)->
      return $scope.permissionToActionMap[permission] || $translate.instant('can_view')
    for ace in file.aces
      # 不显示 everyone 和 owner(现在判断cmis:all是 owner 并不是很准确 后期可能需要修改) 不显示继承的权限  用户组 里面的email都在继承 isDirect false
      # https://jira.foxitsoftware.cn/browse/CBASE-1196
      if ace.userId!='everyone' && ace.permission!='cmis:all' && ace.userId!='guest' && ace.isDirect
        if ace.user && !ace.user.data
          ace.user.getNameForShare().then(()->
            $scope.$broadcast('get-user-info-succ')
          )
        user={
          userId:ace.userId
          userName:ace.user.getName()
          userAvatar:ace.user.getAvatar()
          permission:ace.permission
          action:getActionByPermission(ace.permission)
        }
        $scope.userList.push(user)
    #  user list
  $scope.generateUserList()

  $scope.setShareInfo = (file,shareInfo,postMessage,disableDownload)->
    $scope.showLoading()
    ApiService.setSharedInfo(file,shareInfo,postMessage,disableDownload,(data)->
      $scope.successSetShareInfoCallback(data,file)

    ,(errData)->
      $scope.settingShareInfo = false
      $scope.hideLoading()
      $timeout(()->
        $scope.$apply()
      )
    )
  $scope.appendShareInfo=(file,shareInfo,postMessage)->
    ApiService.appendSharedInfo(file,shareInfo,postMessage,(data)->
      $scope.successSetShareInfoCallback(data,file)
    ,(errData)->
      $scope.settingShareInfo = false
      $timeout(()->
        $scope.$apply()
      )
    )

  $scope.newUserList=[]
  $scope.feedback=false
  $scope.savingNewUser=false
  $('body').on('click','.new-user-list-container',()->
    $('.new-user-list-container textarea').focus()
    return true
  )
  generateUser=(email)->
    return {
      userEmail:email
      isValidInput:Utils.isValidEmail(email) || Utils.isInGroup(email)
      avatar:email

    }
  $scope.addNewUser=()->
#    userList = $scope.emailList()
    if $scope.newEmail
      emailList = $scope.newEmail.replace(/\s+/g,';');
      emailList = emailList.replace(/\,+/g,';');
      emailList = emailList.replace(/\，+/g,';');
      emailList = emailList.replace(/\；+/g,';');
      emailList = emailList.replace(/\;+/g,';');

      if(emailList.indexOf(';')!=-1)
        emailArr = emailList.split(';')
        for email in emailArr
          user = generateUser(email)
          $scope.newUserList.push(user)
      else
        user = generateUser($scope.newEmail)
        $scope.newUserList.push(user)
      $scope.newEmail=''
      event.preventDefault()
  $scope.deleteUser=(index)->

    $scope.newUserList.splice(index,1)

  $scope.handleKeys=(event)->
#    console.log(event);
    # handle ctrl + v paste
#    if event.metaKey==true && event.keyCode==86 || event.ctrlKey==true && event.keyCode==86
    if event.keyCode==8 || event.key=='Backspace'
      if $scope.newUserList.length && !$scope.newEmail
        $scope.newUserList.splice($scope.newUserList.length-1,1)
    # handle 'enter' key 'space' key ';'  ','
    if event.which==13 || event.keyCode==188 || event.keyCode==32 || event.keyCode==186
      if !$scope.newEmail
        if event
          event.preventDefault()
        return false
      else
        $scope.addNewUser()
  $scope.clearNewUserList=()->
    $scope.newUserList=[]
    $scope.newEmail=''
    $scope.feedback=false
    $scope.postMessage=''

  $scope.saveNewUserList=()->
    $scope.$broadcast('add-user')
    if $scope.isCpdfDoc
      shareInfo=[{guest:'cmis:read'}]
    else
      shareInfo=[]
    postMessage=$scope.postMessage
    userList = angular.copy($scope.newUserList)
    for user in userList
      arr={}
      # add valid email
      if !user.isValidInput
        Utils.warning($translate.instant('invalid_email',{'email':user.userEmail}))
        return
      if user.isValidInput
        key = user.userEmail
      # value = user.permission
      # if key is group name set acl need groupId
        if window.sharePlugin && window.sharePlugin.groupsNameArray && window.sharePlugin.groupsNameArray.length>0
          if key in window.sharePlugin.groupsNameArray
            key = window.sharePlugin.groupsNameToIdMap[key]
        value = 'cmis:read'
        arr[key]=value
        shareInfo.push(arr)

    if shareInfo.length>0
      $scope.savingNewUser=true
      $scope.showLoading()

      if CmisService.project=='cpdf360'
      # https://jira.foxitsoftware.cn/browse/CPDF-3273
      # 未注册未审核的邮箱不允许分享
        Utils.disabledEmail=''
        promiseArr=[]
        for userObj in userList
          promiseArr.push(ApiService.checkUserStatus(userObj.userEmail))
        console.log(promiseArr)
        $q.all(promiseArr).then((arr)->
          console.log('====success arr')
          notRegister=[]
          notApproval=[]
          enabledEmail=[]
          for email in arr
            if email.notRegister
              notRegister.push(email.notRegister)
            if email.notApproval
              notApproval.push(email.notApproval)
            else
              enabledEmail.push(email.enabled)
          notRegisterEmails=notRegister.join(' ')
          notApprovalEmails=notApproval.join(' ')
          console.log(notRegisterEmails)
          console.log(notApprovalEmails)
          console.log(enabledEmail)
          if notRegisterEmails=='' && notApprovalEmails ==''
            console.log('shareTo goes here ')
            ApiService.appendSharedInfo(file,shareInfo,postMessage,$scope.feedback,(data)->
              str=''
              if(data.data && data.data.failed_share)
                if data.data.failed_share.length>0
                  str=data.data.failed_share.join(', ')
                  Utils.warning($translate.instant('fail_to_share',{user:str}))
              if(data.data && data.data.need_sign_up_email_array)
                if data.data.need_sign_up_email_array.length>0
                  str1=data.data.need_sign_up_email_array.join(', ')
                  Utils.warning($translate.instant('share_fail_set_acl_but_send_email',{user:str1}))
              if data
                cmisData=data
                cmisData.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
                cmisData.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
                newFile = ModelService.createDocument(cmisData.data.cmis_document)
                if window.FX && window.FX.app && window.FX.app.sendMessage
                  window.FX.app.sendMessage({
                    type:'cmisData',
                    data:cmisData
                  })
                file.description = newFile.description
                file.aces = newFile.aces
                file.disableDownload = newFile.disableDownload
                Utils.sendGaEvent('Document','SendEmail','')
              $scope.hideLoading()
              $timeout(()->
                $scope.generateUserList()
                $scope.savingNewUser=false
                $scope.clearNewUserList()
                $scope.$apply()
              )
            ,(err)->
              console.log(err)
              $scope.hideLoading()
              $scope.savingNewUser=false
            )
          else
            if notRegisterEmails==''
              notRegisterClass='hide'
            if notApprovalEmails==''
              notApprovalClass='hide'
            Utils.warning($translate.instant('not_allow_share',{notRegister:notRegisterEmails,notApproval:notApprovalEmails,notRegisterClass:notRegisterClass,notApprovalClass:notApprovalClass}))
            $scope.savingNewUser=false
            $scope.hideLoading()
            return
          console.log(arr)
        )
      else
        ApiService.appendSharedInfo(file,shareInfo,postMessage,$scope.feedback,(data)->
          str=''
          str1=''
          if(data.data && data.data.failed_share)
            if data.data.failed_share.length>0
              str=data.data.failed_share.join(', ')
              Utils.warning($translate.instant('fail_to_share',{user:str}))
          str1=''
          if(data.data && data.data.need_sign_up_email_array)
            if data.data.need_sign_up_email_array.length>0
              str1=data.data.need_sign_up_email_array.join(', ')
              Utils.warning($translate.instant('share_fail_set_acl_but_send_email',{user:str1}))
          if data
            cmisData=data
            cmisData.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
            cmisData.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
            newFile = ModelService.createDocument(cmisData.data.cmis_document)
            if window.FX && window.FX.app && window.FX.app.sendMessage
              window.FX.app.sendMessage({
                type:'cmisData',
                data:cmisData
              })
            file.description = newFile.description
            file.aces = newFile.aces
            file.disableDownload = newFile.disableDownload
            Utils.sendGaEvent('Document','SendEmail','')
          $scope.hideLoading()
          $timeout(()->
            $scope.generateUserList()
            $scope.savingNewUser=false
            $scope.clearNewUserList()
            $scope.$apply()
          )
        ,(err)->
          console.log(err)
          $scope.hideLoading()
          $scope.savingNewUser=false
        )
    else
      return false






  $scope.timer = null;
  $scope.$on('get-user-info-succ',()->
    if(!$scope.timer)
      $scope.timer = $timeout(()->
        $scope.generateUserList()
        $scope.$apply()
        $scope.timer=null
      ,500)
    else
      $timeout.cancel($scope.timer)
      $scope.timer = $timeout(()->
        $scope.generateUserList()
        $scope.$apply()
        $scope.timer=null
      ,500)
  )
  $scope.getEveryonePermission=(file)->
    everyonePermission=[false,'smx:none']
    for ace in file.aces
      if (ace.userId=='everyone' && ace.isDirect==false) || (ace.userId=='guest' && ace.isDirect==false)
        everyonePermission=[false,ace.permission]
    for ace in file.aces
      if (ace.userId=='everyone' && ace.isDirect==true) || (ace.userId=='guest' && ace.isDirect==true)
        everyonePermission=[true,ace.permission]
    return everyonePermission

  $scope.defaultEveryonePermission = $scope.getEveryonePermission(file)[1] || 'smx:none'
  $scope.everyonePermission = $scope.getEveryonePermission(file)[1] || 'smx:none'
#  $scope.emailBody=$translate.instant('email_body',{
#    fileName:$scope.file.name,
#    curUserEmail:$scope.file.createdBy.data && $scope.file.createdBy.data.display_name || $scope.currentUserEmail,
#    fileSharedLink:$scope.file.sharedLink
#  })
#  $scope.emailSubject=$translate.instant('email_subject',{curUserEmail:$scope.file.createdBy.data && $scope.file.createdBy.data.display_name || $scope.currentUserEmail})
  $scope.setEveryonePermission = (cmisPermission)->
    $scope.everyonePermission = cmisPermission
    Utils.sendGaEvent('Share setting','Set everyone permission',cmisPermission)
    $scope.showChangeTips()

  $scope.showList = [
    $translate.instant('special_people')
    $translate.instant('anyone_has_link')
  ]
  $scope.selectedPermission = 'cmis:read'
  $scope.setGlobalAction = (cmisPermission)->
    $scope.selectedPermission = cmisPermission
    Utils.sendGaEvent('Share setting','Set user permission',cmisPermission)

  $scope.fileLink = file.sharedLink
  $scope.tooltipIsOpen = false
  $scope.copy_status = 'copied_success'
  $scope.errMsg = ''
  $scope.postMessage = ''
  $scope.elemVals={}

  $scope.newUser=[]
  $scope.deletedUser=[]
  $scope.changedUser = {
    originUser:$scope.userList
    newUser:$scope.newUser
    deletedUser:$scope.deletedUser
  }

  $scope.generateBigQrcode = ()->
    qrcodeHtml = $compile('<span qrcode width="120" height="120" url="'+$scope.fileLink+'"></span>')($scope)
    $scope.qrcodeHtml = $(qrcodeHtml[0]).html()
    #  $scope.qrcodeHtml = $sce.trustAsHtml('<b style="color: red">I can</b> have <div class="label label-success">HTML</div> content');
    #  $scope.qrcodeHtml = $sce.trustAsHtml(qrcodeHtml.html())
    $timeout(()->
      $('#popover-qrcode .popover-content').empty().append(qrcodeHtml[0])
    )
    $timeout(()->
      tinyQrcodeEle = $window.document.querySelector('#qrElement')
  #    bigQrcodeEle = $window.document.querySelector('#popover-qrcode')
  #    tinyQrcode={}
  #    bigQrcode={}
  #    bigQrcode.position = $uibPosition.position(bigQrcodeEle)
  #    tinyQrcode.position = $uibPosition.position(tinyQrcodeEle)
  #    console.log(tinyQrcode.position)
  #    console.log(bigQrcode.position)


      #  120 qrcode width 14 padding 2 border
  #    $scope.styles = {
  #      top:tinyQrcode.position.height+'px'
  #      left:tinyQrcode.position.left-Math.abs(120+14*2+4-tinyQrcode.position.width)/2+'px'
  #    }
      $scope.styles = {
        top:48+'px'
        left:177+'px'
      }
  #    console.log($scope.elemVals.position)
    ,300)
  $scope.generateBigQrcode()
  $scope.showBigQrcode = false
  $scope.hideQrcode = ()->
    $scope.showBigQrcode=false
  $scope.showQrcode = ()->
    $scope.showBigQrcode=true

  appSharedLink = {
    google:'https://plus.google.com/share?url='
    facebook:'https://www.facebook.com/share.php?u='
    twitter:'https://twitter.com/intent/tweet?text='
    linkedin:'https://www.linkedin.com/shareArticle?mini=true&url='
    weibo:'http://service.weibo.com/share/share.php?title='

  }
  $scope.getAppSharedApiLink = (appName)->
    link=''
    if appName=='weibo'
      link=appSharedLink[appName]+encodeURIComponent($scope.choseFile.name)+' '
    else
      link=appSharedLink[appName]
    link
  $scope.shareTo = (appName,e)->
#    console.log('====dadada')
    if window.FX && window.FX.app && window.FX.app.sendEmail
      if e
        e.stopPropagation()
        e.preventDefault()
      window.FX.app.sendMessage({
        type:'shareTo',
        appName:appName
      })
      return false
    if appName == 'email'
      return false
    appSharedApiLink = $scope.getAppSharedApiLink(appName)
    if CmisService.device == 'platform-pad'
      cordova.InAppBrowser.open(appSharedApiLink+$scope.fileLink, '_blank', 'hidden=no')
    else
      top = (window.screen.height-365)/2
      left = (window.screen.width-650)/2
#        $timeout(()->
#          if(window.sharePlugin.info.appName.indexOf('MobilePDF')!=-1)
#            FX.app.opencPDFWebPage(appSharedApiLink + encodeURIComponent($scope.file.sharedLink))
#            Utils.sendGaEvent('Share setting','Social share',appName)
#            return false
#        )

      window.open(
        appSharedApiLink+encodeURIComponent($scope.fileLink)
        appName
        "width=650,height=365,left="+left+",top="+top+",resizable,scrollbars=yes,status=1"
      )
    Utils.sendGaEvent('Share setting','Social share',appName)
    return true





  $scope.emailList = ()->
    return (user.userId for user in $scope.userList)

  $scope.validateEmail = ()->
#    console.log('====validate email====')
#    console.log($scope.newEmail)
    if $scope.newEmail==undefined || $scope.newEmail==''
      return true
    emailList = $scope.emailList()
    if !Utils.isValidEmail($scope.newEmail) && !Utils.isInGroup($scope.newEmail)
      $scope.errMsg = 'Not a valid email'
      $scope.errMsg = $translate.instant('not_valid_email')
      return false
    if emailList.indexOf($scope.newEmail) > -1
      $scope.errMsg = 'Email existed'
      $scope.errMsg = $translate.instant('email_existed')
      return false

    $scope.errMsg=''
    $scope.addEmail()
    return true


  $scope.addEmail = ()->
    newUser = {
      userId:$scope.newEmail
      userName:Utils.getEmailPrefix($scope.newEmail)
      userAvatar:'/img/ananymous-avatar.png'
      action:$scope.permissionToActionMap[$scope.selectedPermission]
      permission:$scope.selectedPermission
      isOwner:false
    }
    $scope.newUser.push(newUser)
    $scope.userList.push(newUser)
    $scope.showChangeTips()
    Utils.sendGaEvent('Share setting','Add email',$scope.newEmail)
    $scope.newEmail=''


  $scope.deleteEmail = (index)->
    Utils.sendGaEvent('Share setting','Remove email',$scope.userList[index]['userId'])
    $scope.userList.splice(index,1)
    $scope.showChangeTips()
    $scope.newUser
  $scope.changeDisableDownload = ()->
    $scope.changed=true
    $scope.showChangeTips()
  $scope.handleEnterKey=(e)->
    $scope.errMsg=''
    if e.which==13
      $scope.validateEmail()

  $scope.setUserAction = (user,cmisPermission)->
    user.action=$scope.permissionToActionMap[cmisPermission]
    user.permission=cmisPermission
    $scope.showChangeTips()
    Utils.sendGaEvent('Share setting','Change permission','')


  $scope.copyOnSuccess = (e)->
#    console.info('Action:', e.action)
#    console.info('Text:', e.text)
#    console.info('Trigger:', e.trigger)
#    e.clearSelection()
    timer = $timeout(()->
      $scope.copy_status = $translate.instant('Copied')
      $scope.tooltipIsOpen = true
    )
    $timeout(()->
      $scope.tooltipIsOpen = false
    ,3000)
    Utils.sendGaEvent('Share setting','Copy link',$scope.fileLink)

  $scope.copyOnError = (e)->
#    console.error('Action:', e.action)
#    console.error('Trigger:', e.trigger)
    $timeout(()->
      $scope.copy_status = 'copy_failed'
      $scope.tooltipIsOpen = true
    )
    $timeout(()->
      $scope.tooltipIsOpen = false
    ,3000)
  $scope.successSetShareInfoCallback = (data,file)->
    str=''
    if(data.data && data.data.failed_share)
      if data.data.failed_share.length>0
        str=data.data.failed_share.join(', ')
        Utils.warning($translate.instant('fail_to_share',{user:str}))
    str1=''
    if(data.data && data.data.need_sign_up_email_array)
      if data.data.need_sign_up_email_array.length>0
        str1=data.data.need_sign_up_email_array.join(', ')
        Utils.warning($translate.instant('share_fail_set_acl_but_send_email',{user:str1}))

    data.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
    data.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
    newFile = ModelService.createDocument(data.data.cmis_document)
    file.description = newFile.description
#    if (window.cReaderEnable=='1'||window.cReaderEnable==true||window.cReaderEnable==1) && window.cReaderUrl
#      shareCode=newFile.description.short_code
#      file.sharedLink = window.cReaderUrl+'/share/'+shareCode
#    else
    file.sharedLink = newFile.sharedLink
#    console.log('=======old file======')

#    file.getAces(null,null,true)
    callback = (cmisData)->
      if cmisData
        data=cmisData
        cmisData.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
        cmisData.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
        newFile = ModelService.createDocument(cmisData.data.cmis_document)
        file.description = newFile.description
        file.aces = newFile.aces
        file.disableDownload = newFile.disableDownload
      if window.FX && window.FX.app && window.FX.app.sendMessage
        window.FX.app.sendMessage({
          type:'cmisData',
          data:data
        })
      $timeout(()->
        $scope.$apply()
      )
      # ga and
      Utils.sendGaEvent('Share setting','Save Changes','')
      Utils.success($translate.instant('set_share_suc'))
      $scope.settingShareInfo = false
      if (window.formPreviewAndShare && window.formPreviewAndShare == true && window.parent && window.parent.document.getElementById('cloud-reading-iframe'))
        console.log("reload cloud reading iframe")
        window.parent.document.getElementById('cloud-reading-iframe').contentWindow.location.reload(true)

      # close modal
      if(window.FX && window.FX.app && window.FX.app.closeDialog)
        FX.app.closeDialog()
      $scope.hideLoading()
      $uibModalInstance.close()

    if file.getShareCode()
      ApiService.setDownloadPerm(file.getShareCode(),$scope.disableDownload,(data)->
        callback(data)
      ,(data)->
        callback()
      )
    else
      callback(data)



  $scope.stopSharing=false
  $scope.stopShare=()->
    $scope.stopSharing=true
    $scope.showLoading()
    ApiService.stopShare(file.id,(data)->
      $scope.stopSharing=false
      $scope.successSetShareInfoCallback(data,file)
    ,(err)->
      $scope.stopSharing=false
      $scope.hideLoading()
      Utils.warning(err)
      $timeout(()->
        $scope.$apply()
      )
    )
  $scope.ok = ()->
#    if($scope.newEmail!='')
#      $scope.validateEmail()
    # 发送的 请求 只关注 两个  一个是新增用户 一个是删除的用户
    if $scope.settingShareInfo == true
      return false

    if $scope.validateEmail()==false
      return

    if !$scope.changed
      if window.FX && window.FX.app && window.FX.app.closeDialog
        FX.app.closeDialog()
      $uibModalInstance.close()
      return
    $scope.settingShareInfo = true
    if $scope.isCpdfDoc
      shareInfo=[{guest:'cmis:read'}]
    else
      shareInfo=[]
    everyoneData = {
      "guest": $scope.everyonePermission
    }
    if $scope.everyonePermission != 'smx:none'
      shareInfo.push(everyoneData)
    userList = angular.copy($scope.userList)
    userList.shift()
    for user in userList
      arr={}
      key = user.userId
#      value = user.permission
      value = 'cmis:read'
      arr[key]=value
      shareInfo.push(arr)
    console.log('defaultEveryonePermission',$scope.defaultEveryonePermission)
    console.log('everyonePermission',$scope.everyonePermission)
    console.log('everyoneData',everyoneData)
    console.log('shareInfo',shareInfo)
    console.log('postMessage',$scope.postMessage)
    console.log('$scope.userList',$scope.userList)

    if shareInfo.length>=0
      if $scope.postMessage
        Utils.sendGaEvent('Share setting','Email content','')
      if CmisService.project=='cpdf360'
        #https://jira.foxitsoftware.cn/browse/CPDF-3273
        # 未注册的邮箱不允许分享
        $scope.setShareInfo(file,shareInfo,$scope.postMessage,$scope.disableDownload)
        promiseArr=[]
#        for userObj in userList
#          promiseArr.push(ApiService.checkUserStatus(userObj.id||userObj.userId))
#        console.log(promiseArr)
#        $q.all(promiseArr).then((arr)->
#          console.log('====success arr')
#          console.log(arr)
#        ,(arr)->
#          console.log('====err arr')
#          console.log(arr)
#        )
      else
        $scope.setShareInfo(file,shareInfo,$scope.postMessage,$scope.disableDownload)
      return true

  $scope.showChangeTips = ()->
    $('.modal-footer .alert.alert-success').removeClass('hide')
    $scope.changed = true
    adjustModalHeight()
    return true
  $scope.closeChangeTips = ()->
    $('.modal-footer .alert.alert-success').addClass('hide')
    return false

  $scope.cancel = ()->
    Utils.sendGaEvent('Share setting','Click cancel button','close share modal')
    if(window.FX && window.FX.app && window.FX.app.closeDialog)
      FX.app.closeDialog()
    $uibModalInstance.close()


  if !$.fn.dropdown
    clearMenus = (e) ->
      if e and e.which == 3
        return
      $(backdrop).remove()
      $(toggle).each ->
        $this = $(this)
        $parent = getParent($this)
        relatedTarget = relatedTarget: this
        if !$parent.hasClass('open')
          return
        $parent.trigger e = $.Event('hide.bs.dropdown', relatedTarget)
        if e.isDefaultPrevented()
          return
        $this.attr 'aria-expanded', 'false'
        $parent.removeClass('open').trigger 'hidden.bs.dropdown', relatedTarget
        return
      return

    getParent = ($this) ->
      selector = $this.attr('data-target')
      if !selector
        selector = $this.attr('href')
        selector = selector and /#[A-Za-z]/.test(selector) and selector.replace(/.*(?=#[^\s]*$)/, '')
      # strip for ie7
      $parent = selector and $(selector)
      if $parent and $parent.length then $parent else $this.parent()

  # DROPDOWN PLUGIN DEFINITION
  # ==========================

    Plugin = (option) ->
      @each ->
        $this = $(this)
        data = $this.data('bs.dropdown')
        if !data
          $this.data 'bs.dropdown', data = new Dropdown(this)
        if typeof option == 'string'
          data[option].call $this
        return

    'use strict'
  # DROPDOWN CLASS DEFINITION
  # =========================
    backdrop = '.dropdown-backdrop'
    toggle = '[data-toggle="dropdown"]'

    Dropdown = (element) ->
      $(element).on 'click.bs.dropdown', @toggle
      return

    Dropdown.VERSION = '3.3.4'

    Dropdown::toggle = (e) ->
      $this = $(this)
      if $this.is('.disabled, :disabled')
        return
      $parent = getParent($this)
      isActive = $parent.hasClass('open')
      clearMenus()
      if !isActive
        if 'ontouchstart' of document.documentElement and !$parent.closest('.navbar-nav').length
  # if mobile we use a backdrop because click events don't delegate
          $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on 'click', clearMenus
        relatedTarget = relatedTarget: this
        $parent.trigger e = $.Event('show.bs.dropdown', relatedTarget)
        if e.isDefaultPrevented()
          return
        $this.trigger('focus').attr 'aria-expanded', 'true'
        $parent.toggleClass('open').trigger 'shown.bs.dropdown', relatedTarget
      false

    Dropdown::keydown = (e) ->
      if !/(38|40|27|32)/.test(e.which) or /input|textarea/i.test(e.target.tagName)
        return
      $this = $(this)
      e.preventDefault()
      e.stopPropagation()
      if $this.is('.disabled, :disabled')
        return
      $parent = getParent($this)
      isActive = $parent.hasClass('open')
      if !isActive and e.which != 27 or isActive and e.which == 27
        if e.which == 27
          $parent.find(toggle).trigger 'focus'
        return $this.trigger('click')
      desc = ' li:not(.disabled):visible a'
      $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
      if !$items.length
        return
      index = $items.index(e.target)
      if e.which == 38 and index > 0
        index--
      # up
      if e.which == 40 and index < $items.length - 1
        index++
      # down
      if ! ~index
        index = 0
      $items.eq(index).trigger 'focus'
      return

    old = $.fn.dropdown
    $.fn.dropdown = Plugin
    $.fn.dropdown.Constructor = Dropdown
  # DROPDOWN NO CONFLICT
  # ====================

    $.fn.dropdown.noConflict = ->
      $.fn.dropdown = old
      this

  # APPLY TO STANDARD DROPDOWN ELEMENTS
  # ===================================
    $(document).on('click.bs.dropdown.data-api', clearMenus).on('click.bs.dropdown.data-api', '.dropdown form', (e) ->
      e.stopPropagation()
      return
    ).on('click.bs.dropdown.data-api', toggle, Dropdown::toggle).on('keydown.bs.dropdown.data-api', toggle, Dropdown::keydown).on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown::keydown).on 'keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown::keydown
    return

# ---
# generated by js2coffee 2.2.0
)
